
import cloud from '@lafjs/cloud'
import {ok} from "@/utils/responseUtil";
import nw from "nw-lafjs";
const db = cloud.database()
const _ = db.command
async function getActivityReduceAmount(catInfoNeed: any[]) {
    let activityReduceAmount = 0
    let skuIdCatMap = new Map()
    let skuIds = []
    for (let i = 0; i < catInfoNeed.length; i++) {
        let each = catInfoNeed[i]
        skuIds.push(each.skuId)
        skuIdCatMap.set(each.skuId,catInfoNeed)
    }
    let activitySkus = await nw.db.findListByWhereJson({
        dbName:"activitySku",
        whereJson:{deleted:0,skuId:_.in(skuIds)}
    })
    if (nw.util.isNull(activitySkus)||activitySkus.length===0){
        return Promise.resolve(activityReduceAmount)
    }
    let ruleSkuMap = new Map()
    let activityIds = []
    for (let i = 0; i < activitySkus.length; i++) {
        let each = activitySkus[i]
        activityIds.push(each.activityId)
        if (ruleSkuMap.has(each.activityId)){
            ruleSkuMap.get(each.activityId).push(each.skuId)
        }else {
            ruleSkuMap.set(each.activityId,[each.skuId])
        }
    }
    let now = new Date()
    //查询符合今天的活动
    let actovity = await nw.db.findListByWhereJson({
        dbName:"activityInfo",
        whereJson:{deleted:0,_id:_.in(activityIds),startTime:_.lte(now),endTime:_.gte(now)}
    })
    if (nw.util.isNull(actovity)||actovity.length===0){
        return Promise.resolve(activityReduceAmount)
    }
    //查询activityRule
    let actovityNeedIds = actovity.map(item=>item._id)
    let activityRules = await nw.db.findListByWhereJson({
        dbName:"activityRule",
        whereJson:{deleted:0,activityId:_.in(actovityNeedIds)}
    })
    if (nw.util.isNull(activityRules)||activityRules.length===0){
        return Promise.resolve(activityReduceAmount)
    }
    //计算活动优惠金额
    for (let i = 0; i < activityRules.length; i++) {
        let rule = activityRules[i]
        if (rule.activityType===1){
            //满减
            let activityId = rule.activityId
            //看看有哪些sku适合该计算规则
            if (!ruleSkuMap.has(activityId)){
                continue//没有的话，直接跳过计算
            }
            let skuIds = ruleSkuMap.get(activityId)
            //计算是否达到要求
            let amount = 0
            for (let j = 0; j < skuIds.length; j++) {
                if (!skuIdCatMap.has(skuIds[i])){
                    continue
                }
                let carInfo = skuIdCatMap.get(skuIds[i])
                amount =amount+ carInfo.cartPrice*carInfo.skuNum
            }
            if (amount>=rule.conditionAmount){
                //达到满减要求
                activityReduceAmount = activityReduceAmount+rule.conditionAmount
            }
        }else if (rule.activityType===2){
            //折扣
            let activityId = rule.activityId
            //看看有哪些sku适合该计算规则
            if (!ruleSkuMap.has(activityId)){
                continue//没有的话，直接跳过计算
            }
            let skuIds = ruleSkuMap.get(activityId)
            //计算是否达到要求
            let count = 0
            let amount = 0
            for (let j = 0; j < skuIds.length; j++) {
                if (!skuIdCatMap.has(skuIds[i])){
                    continue
                }
                let carInfo = skuIdCatMap.get(skuIds[i])
                amount =amount+ carInfo.cartPrice*carInfo.skuNum
                count = count+carInfo.skuNum
            }
            if (count>=rule.conditionNum){
                //达到满减要求
                activityReduceAmount = activityReduceAmount+(amount*rule.benefitDiscount/100)
            }
        }
    }

    return Promise.resolve(activityReduceAmount)

}

async function getCouponInfoList(userId: any, catInfoNeed: any[]) {
    //初始化返回结果
    let data = {
        couponInfoList:[],
        couponReduceAmount:0
    }
    //1.查询全部未使用的优惠券id
    let couponUse = await nw.db.findListByWhereJson({
        dbName:"couponUse",
        whereJson:{deleted:0,userId:userId,couponStatus:1}
    })
    if (nw.util.isNull(couponUse)||couponUse.length===0){
        return Promise.resolve(data)
    }
    //2.查询优惠券信息和使用范围信息
    let couponIds = couponUse.map(item=>item.couponId)
    let couponInfos = await nw.db.findListByWhereJson({
        dbName:"couponInfo",
        whereJson:{_id:_.in(couponIds)}
    })
    if (nw.util.isNull(couponInfos)||couponInfos.length===0){
        return Promise.resolve(data)
    }
    let skuCouponMap = new Map()
    let categoryCouponMap = new Map()
    let allCoupons = []
    //3.查询使用规则
    for (let i = 0; i < couponInfos.length; i++) {
        let each = couponInfos[i]
        switch (each.rangeType) {
            case 1:
                allCoupons.push(each)
                break
            case 2:
                categoryCouponMap.set(each._id,each)
                break
            case 3:
                skuCouponMap.set(each._id,each)
                break
        }
    }
    let couponRanges = await nw.db.findListByWhereJson({
        dbName:"couponRange",
        whereJson:{deleted:0,couponId:_.in(couponIds)}
    })
    let rangeCouponMap = new Map()
    if (!nw.util.isNull(couponRanges)&&couponRanges.length>0){
        for (let i = 0; i < couponRanges.length; i++) {
            let each = couponRanges[i]
            if (categoryCouponMap.has(each.couponId)){
                categoryCouponMap.get(each.couponId).push(each.rangeId)
            }else {
                categoryCouponMap.set(each.couponId,[each.rangeId])
            }
            if (rangeCouponMap.has(each.rangeId)){
                rangeCouponMap.get(each.rangeId).push(each.couponId)
            }else {
                rangeCouponMap.set(each.rangeId,[each.couponId])
            }
        }
    }
    //计算扣减金额
    for (let i = 0; i < catInfoNeed.length; i++) {
        let catInfo = catInfoNeed[i]
        //折扣顺序,sku>category>all
        if (rangeCouponMap.has(catInfo.skuId)){
            //sku
            let couponIds = rangeCouponMap.get(catInfo.skuId)
            for (let j = 0; j < couponIds.length; j++) {
                let coupon = skuCouponMap.get(couponIds[i])
                if (coupon.conditionAmount>0&&(coupon.conditionAmount>(catInfo.cartPrice*catInfo.skuNum))){
                    //没有达到使用条件
                    continue
                }
                //达到使用条件
                data.couponInfoList.push(coupon)
                data.couponReduceAmount = data.couponReduceAmount+coupon.amount
            }
        }else if (rangeCouponMap.has(catInfo.categoryId)){
            let couponIds = rangeCouponMap.get(catInfo.categoryId)
            for (let j = 0; j < couponIds.length; j++) {
                let coupon = categoryCouponMap.get(couponIds[i])
                if (coupon.conditionAmount>0&&(coupon.conditionAmount>(catInfo.cartPrice*catInfo.skuNum))){
                    //没有达到使用条件
                    continue
                }
                //达到使用条件
                data.couponInfoList.push(coupon)
                data.couponReduceAmount = data.couponReduceAmount+coupon.amount
            }
        }else if (allCoupons.length>0){
            //通用优惠券
            allCoupons.sort((a,b)=>b.amount-a.amount)//倒序排列
            let coupon = allCoupons.shift()
            if (coupon.conditionAmount>0&&(coupon.conditionAmount>(catInfo.cartPrice*catInfo.skuNum))){
                //没有达到使用条件
                continue
            }
            //达到使用条件
            data.couponInfoList.push(coupon)
            data.couponReduceAmount = data.couponReduceAmount+coupon.amount
        }
    }

    return Promise.resolve(data)
}

export default async function (ctx: FunctionContext) {
    let userId = ctx.user.admin
    /**
     * {
     *   "cartInfoList": [],
     *   "activityReduceAmount": [],
     *   "couponInfoList": [],
     *   "couponReduceAmount": [],
     *   "originalTotalAmount": 0,
     *   "totalAmount": []
     * }
     */


    //初始化返回数据结构
    let result = {
        "cartInfoList": [],
        "activityReduceAmount": 0.00,
        "couponInfoList": [],
        "couponReduceAmount": 0.00,
        "originalTotalAmount": 0.00,
        "totalAmount": 0.00
    }

    //1.查询全部的购物车
    let carInfos = await nw.db.findListByWhereJson({
        dbName:"cartInfo",
        whereJson:{deleted:0,userId:userId,status:1}
    })
    if (nw.util.isNull(carInfos)){
        return ok(result)
    }
    result.cartInfoList = carInfos.map(item=>{
        item.id = item._id
        return item
    })
    //计算总金额
    let originalTotalAmount = 0
    let catInfoNeed = []
    for (let i = 0; i < carInfos.length; i++) {
        let carInfo = carInfos[i];
        if (carInfo.isChecked===0){
            continue  //没有选中则直接跳过即可
        }
        originalTotalAmount = originalTotalAmount+carInfo.cartPrice*carInfo.skuNum
        catInfoNeed.push(carInfo)
    }
    result.originalTotalAmount = originalTotalAmount
    if (catInfoNeed.length>0){
        //计算活动抵扣金额
        let activityReduceAmount = await getActivityReduceAmount(catInfoNeed)
        result.activityReduceAmount = activityReduceAmount
        //计算优惠券抵扣金额
        let {couponInfoList,couponReduceAmount} = await getCouponInfoList(userId,catInfoNeed)
        result.couponInfoList = couponInfoList
        result.couponReduceAmount = couponReduceAmount
    }
    //计算实际支付金额
    result.totalAmount = result.originalTotalAmount-(result.activityReduceAmount+result.couponReduceAmount)
    // @ts-ignore
    result.carInfoVoList = result.cartInfoList
    return ok(result)
}
